#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <functional>
#include <memory>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "nocopy.hpp"

using namespace LogModule;
using namespace ThreadPoolModule;

const static int gsockfd = -1;
// const std::string gdefaultip = "127.0.0.1"; // 本地环回地址
const uint16_t gdefaultport = 8080; 

using adduser_t = std::function<void(InetAddr&)>;
using deluser_t = std::function<void(InetAddr&)>;
using router_t = std::function<void(int sockfd, const std::string& message)>;
using task_t = std::function<void()>;

class UdpServer : public nocopy
{
public:
    UdpServer(const uint16_t port = gdefaultport)
    :_sockfd(gsockfd)
    ,_addr(port)
    ,_isrunning(false)
    {}

    void InitServer()
    {
        // 1.创建套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is: " << _sockfd;

        // 2.填充网络信息并绑定
        // struct sockaddr_in local;
        // bzero(&local, sizeof(local));
        // local.sin_family = AF_INET;
        // local.sin_port = ::htons(_port);
        // local.sin_addr.s_addr = ::inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void RegisterService(adduser_t adduser, deluser_t deluser, router_t router)
    {
        _adduser = adduser;
        _deluser = deluser;
        _router = router;
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer)-1, 0, CONV(&peer), &len); 
            if (n > 0)
            {
                inbuffer[n] = 0;
                // std::string clientip = ::inet_ntoa(peer.sin_addr);
                // uint16_t clientport = ::ntohs(peer.sin_port);
                InetAddr cli(peer);
                std::string clientinfo;
                if (strcmp(inbuffer, "QUIT") == 0)
                {
                    _deluser(cli);
                    clientinfo = "[" + cli.Addr() + "]" + "我走了，你们聊！";
                }
                else
                {
                    // 添加用户
                    _adduser(cli);

                    clientinfo = "[" + cli.Addr() + "]" + inbuffer;
                    // LOG(LogLevel::INFO) << clientinfo;
                }

                ThreadPool<task_t>::GetInstance()->Equeue(std::bind(_router, _sockfd, clientinfo));
                // std::string echo_string = "echo# ";
                // echo_string += inbuffer;
                // ::sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, CONV(&peer), sizeof(peer));
            }

        } 
        _isrunning = false;
    }

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }
private:
    int _sockfd;        // 创建socket返回的fd
    InetAddr _addr;     
    // std::string _ip;    // 服务器IP
    // uint16_t _port;     // 服务器端口号
    bool _isrunning;    // 服务是否启动

    adduser_t _adduser;
    deluser_t _deluser;
    router_t _router;
};